<template>
    <div>
       <input type="file" ref="fileRef" @change="uploadFile"><br>
       <progress :value="value" max="100"></progress>
       <span>{{value}}%</span>
       <div>
          <button @click="cancelUpload">取消</button>
       </div>
       <div>
        {{errMsg}}
       </div>
    </div>
</template>

<script>
import axios from 'axios'
const {CancelToken,isCancel}=axios
export default {
  data(){
    return{
      value:0,
      errMsg:''
    }
  },
  methods:{
    async uploadFile(){
      const fd=new FormData()
      fd.append("file",this.$refs.fileRef.files[0])
      const result=await axios({
        method:'POST',
        url:'http://www.zhaijizhe.cn:3005/upload/uploadFile',
        data:fd,
        headers:{
          'Content-Type':"multipart/form-data"
        },
        onUploadProgress:(e)=>{
          this.value=Number(e.progress*100).toFixed(2)
        },
        cancelToken:new CancelToken((arg)=>{
          this.cancel=arg
        })
      }).catch(err=>{
        if(isCancel(err)){
           this.errMsg="取消上传文件"
        }
      })

    },
    cancelUpload(){
      if(this.cancel){
        console.log('***********');
        //调用该函数完成取消
        this.cancel()
      }
    }
  }
}
</script>

<style>

</style>